package com.javasoft.service.YZX.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasoft.dao.YZX.ClassResultsDao;
import com.javasoft.dao.YZX.PaperInquiryDao;
import com.javasoft.entity.WJC.StudentAnswer;
import com.javasoft.entity.YZX.ClassResults;
import com.javasoft.service.YZX._interface.ClassResultsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("classResultsService")
@Slf4j

public class ClassResultsServiceImpl extends ServiceImpl<ClassResultsDao, ClassResults> implements ClassResultsService {


    @Autowired
    private PaperInquiryDao paperInquiryDao;


    @Override
    public void calculateAndStoreClassResults() {
        // 查询所有记录并按班级分组
        List<StudentAnswer> answers = paperInquiryDao.selectList(null);

        // 按班级和考试ID双重分组，确保examId转换为String
        Map<String, Map<String, List<StudentAnswer>>> groupedByClassAndExam = answers.stream()
                .collect(Collectors.groupingBy(
                        StudentAnswer::getUserClass,
                        Collectors.groupingBy(answer -> String.valueOf(answer.getExamId())) // 将examId转换为String
                ));

        for (Map.Entry<String, Map<String, List<StudentAnswer>>> classEntry : groupedByClassAndExam.entrySet()) {
            String className = classEntry.getKey();
            for (Map.Entry<String, List<StudentAnswer>> examEntry : classEntry.getValue().entrySet()) {
                String examIdStr = examEntry.getKey(); // 现在是String类型的examId
                List<StudentAnswer> classAnswers = examEntry.getValue();

                if (classAnswers.isEmpty()) {
                    log.warn("No answers found for class: {} and examId: {}", className, examIdStr);
                    continue; // 如果没有答案，则跳过这个分组
                }




                // 计算平均分
                double averageScore = classAnswers.stream()
                        .mapToInt(StudentAnswer::getTotalScore)
                        .average()
                        .orElse(0.0);
                BigDecimal avgDecimal = new BigDecimal(averageScore).setScale(2, BigDecimal.ROUND_HALF_UP);

                // 初始化题目正确率统计
                int[] correctCounts = new int[30];
                for (StudentAnswer answer : classAnswers) {
                    // 使用getter方法获取judge字段值
                    correctCounts[0] += answer.getJudge1();
                    correctCounts[1] += answer.getJudge2();
                    correctCounts[2] += answer.getJudge3();
                    correctCounts[3] += answer.getJudge4();
                    correctCounts[4] += answer.getJudge5();
                    correctCounts[5] += answer.getJudge6();
                    correctCounts[6] += answer.getJudge7();
                    correctCounts[7] += answer.getJudge8();
                    correctCounts[8] += answer.getJudge9();
                    correctCounts[9] += answer.getJudge10();
                    correctCounts[10] += answer.getJudge11();
                    correctCounts[11] += answer.getJudge12();
                    correctCounts[12] += answer.getJudge13();
                    correctCounts[13] += answer.getJudge14();
                    correctCounts[14] += answer.getJudge15();
                    correctCounts[15] += answer.getJudge16();
                    correctCounts[16] += answer.getJudge17();
                    correctCounts[17] += answer.getJudge18();
                    correctCounts[18] += answer.getJudge19();
                    correctCounts[19] += answer.getJudge20();
                    correctCounts[20] += answer.getJudge21();
                    correctCounts[21] += answer.getJudge22();
                    correctCounts[22] += answer.getJudge23();
                    correctCounts[23] += answer.getJudge24();
                    correctCounts[24] += answer.getJudge25();
                    correctCounts[25] += answer.getJudge26();
                    correctCounts[26] += answer.getJudge27();
                    correctCounts[27] += answer.getJudge28();
                    correctCounts[28] += answer.getJudge29();
                    correctCounts[29] += answer.getJudge30();
                }

                // 计算题目正确率
                double[] questionRates = new double[30];
                if (!classAnswers.isEmpty()) {
                    for (int i = 0; i < 30; i++) {
                        double rate = ((double) correctCounts[i]) / classAnswers.size();
                        questionRates[i] = new BigDecimal(rate).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    }
                }

                // 插入或更新 class_results 表
                ClassResults result = new ClassResults();
                result.setClassName(className); // 设置String类型的className
                result.setExamId(classAnswers.get(0).getExamId());
                result.setAverage(avgDecimal.doubleValue());

                for (int i = 0; i < 30; i++) {
                    try {
                        Field field = ClassResults.class.getDeclaredField("que" + (i + 1));
                        field.setAccessible(true);
                        field.set(result, questionRates[i]);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        log.error("Error setting question rates: {}", e.getMessage(), e);
                    }
                }

                // 检查是否已存在该班级和考试ID的记录，如果存在则更新，否则插入新记录
                LambdaQueryWrapper<ClassResults> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ClassResults::getClassName, className)
                        .eq(ClassResults::getExamId, result.getExamId());

                ClassResults existingResult = getOne(queryWrapper);
                if (existingResult != null) {
                    result.setId(existingResult.getId());
                    updateById(result);
                } else {
                    save(result);
                }
            }
        }
    }
}